import 'package:website.core/core/domain/stores/user_store.dart';
import 'package:website.core/core/domain/entities/user_content.dart';
import 'package:website.core/core/domain/repositories/user_local_repository/repository.dart';

abstract class InitializeStorages {
  Future<void> call();
}

class InitializeStoragesImpl implements InitializeStorages {
  const InitializeStoragesImpl({
    required UserStore userStore,
    required UserLocalRepository userLocalRepository,
  })  : _userStore = userStore,
        _userLocalRepository = userLocalRepository;

  final UserStore _userStore;
  final UserLocalRepository _userLocalRepository;

  @override
  Future<void> call() async {
    await _userStore.initialize(
      modules: [
        'user',
      ],
    );

    await Future.wait([
      _handleUserContentMigration(),
    ]);
  }

  Future<void> _handleUserContentMigration() async {
    final currentVersion = await _userLocalRepository.getCurrentVersion();
    final lastVersion = _userLocalRepository.lastVersion;

    if (currentVersion == lastVersion) {
      return;
    }

    if (currentVersion == null) {
      const userContent = UserContent(
        accessCredentials: null,
        user: null,
      );

      await _userLocalRepository.saveContent(
        userContent: userContent,
        version: lastVersion,
      );
    }
  }
}
